package com.bigboss.knowstar.service.impl;

import com.bigboss.knowstar.entity.Doc;
import com.bigboss.knowstar.entity.Folder;
import com.bigboss.knowstar.entity.Tag;
import com.bigboss.knowstar.exception.DocException;
import com.bigboss.knowstar.exception.FolderException;
import com.bigboss.knowstar.exception.TagException;
import com.bigboss.knowstar.mapper.DocMapper;
import com.bigboss.knowstar.mapper.TagMapper;
import com.bigboss.knowstar.service.IDocService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class DocServiceImpl implements IDocService {

    @Autowired
    private DocMapper docMapper;

    @Autowired
    private TagMapper tagMapper;

    @Override
    public void createDoc(Integer Fid, Doc doc) {
        if (doc.getDname() == null) {
            throw new DocException("请填写文档名称");
        }
        doc.setDFid(Fid);
        doc.setDcreateTime(new Date());
        doc.setDvisible(true);
        doc.setDpath("");
        doc.setDsize(100L);
        doc.setDtype("pdf");
        int res = docMapper.createDoc(doc);
        if (res == 0) {
            throw new DocException("文档创建失败");
        }
    }

    @Override
    public void updateDoc(Integer Did, Map<String, Object> fields) {
        int res = docMapper.updateDoc(Did, fields);
        if (res == 0) {
            throw new DocException("更新文档信息失败");
        }
    }

    @Override
    public void deleteDoc(Integer Did) {
        int res = docMapper.deleteDoc(Did);
        if (res == 0) {
            throw new DocException("删除文档失败");
        }
    }

    @Override
    public Doc getDoc(Integer Did) {
        Doc doc = docMapper.getDoc(Did);
        if (doc == null) {
            throw new DocException("当前文档不存在");
        }
        return doc;
    }

    @Override
    public void createDocTag(Integer Did, Tag tag) {
        int Tid = tagMapper.isTnameExist(tag.getTname());
        if (Tid == 0) {
            // 标签名不存在，则创建新的标签
            tag.setTcreateTime(new Date());
            tag.setTvisible(true);
            int res = tagMapper.createTag(tag);
            if (res == 0) {
                throw new TagException("标签创建失败");
            }
            Tid = tagMapper.getTagByTname(tag.getTname()).getTid();
        }
        // 标签名存在
        docMapper.createDocTag(Did, Tid);
    }

    @Override
    public List<Tag> getDocTags(Integer Did) {
        return docMapper.getDocTags(Did);
    }
}
